package com.sunny.utils;

import java.util.Random;

/**
 * ID成器
 * 
 * @author Catkin_nice
 *
 */
public class Sequence {

	// 应用层缓存的序列号数量，可以提升序列号发放的性能，不用频繁更新数据库。
	private static final int CACHE_SIZE = 1000;

    private static int count = CACHE_SIZE;
    private static long index = 1;

	private static void getSequenceValue() {
		// TODO 序列ID从缓存获取
		/*String cacheId = cache.get(key);
		if (cacheId == null) {
			cache.set(key, CACHE_SIZE);
		} else {
			cache.incr(key, CACHE_SIZE);
			index = Long.parseLong(cacheId);
		}*/
	}

	public synchronized static long getNextId() {
		// 如果发放的序列号小于缓存的个数，则通过缓存发放一个序列号
		if (count < CACHE_SIZE) {
			count++;
			index++;
		} else {		// 获取一组序列号，缓存
			count = 1;
			getSequenceValue();
		}

//		long id = index * 100 + ConfigUtil.getConfig().getServerId(); //集群方案
		return index;
	}
	
	public synchronized static String getNextOrderId() {
		StringBuilder builder = new StringBuilder("SM");
		builder.append(randomString(4));
		builder.append(getNextId());
		return builder.toString();
	}
	
	public static String randomString(int length) {
		Random random = new Random();
		StringBuilder builder = new StringBuilder();
		String str = "1234567890QWERTYUIOPASDFGHJKLZXCVBNM";
		
		for (int i = 0; i < length; i++) {
			builder.append(str.charAt(random.nextInt(str.length())));
		}
		return builder.toString();
	}
}
